/**
 * jims
 */
package com.jims.master.modules.doctor.service;

import com.jims.master.common.data.StringData;
import com.jims.master.common.persistence.Page;
import com.jims.master.common.service.CrudService;
import com.jims.master.common.utils.ChineseCharToEnUtils;
import com.jims.master.common.utils.DateUtils;
import com.jims.master.common.utils.PrintPdfUtils;
import com.jims.master.common.utils.StringUtils;
import com.jims.master.common.web.impl.BaseDto;
import com.jims.master.modules.doctor.dao.*;
import com.jims.master.modules.doctor.entity.*;
import com.jims.master.modules.finance.dao.PatPrepaymentDao;
import com.jims.master.modules.finance.dao.RegistCostDao;
import com.jims.master.modules.finance.entity.PatPrepayment;
import com.jims.master.modules.finance.entity.RegistCost;
import com.jims.master.modules.med.entity.MedicalVsPatient;
import com.jims.master.modules.med.service.MedicalCardConsumeMasterService;
import com.jims.master.modules.med.service.MedicalVsPatientService;
import com.jims.master.modules.oper.dao.PriceListDao;
import com.jims.master.modules.oper.entity.PriceList;
import com.jims.master.modules.physical.dao.TInformationDao;
import com.jims.master.modules.reg.dao.ClinicForRegistDao;
import com.jims.master.modules.reg.dao.ClinicIndexDao;
import com.jims.master.modules.reg.entity.ClinicForRegist;
import com.jims.master.modules.reg.entity.ClinicIndex;
import com.jims.master.modules.sys.dao.CompanyDao;
import com.jims.master.modules.sys.dao.OrgDeptDao;
import com.jims.master.modules.sys.dao.SysOrgDictDao;
import com.jims.master.modules.sys.entity.User;
import com.jims.master.modules.sys.utils.DictUtils;
import com.jims.master.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 病人基本信息Service
 * @author 赵宁
 * @version 2017-02-28
 */
@Service
@Transactional(readOnly = true)
public class PatMasterIndexService extends CrudService<PatMasterIndexDao, PatMasterIndex> {
    @Autowired
	private PatMasterIndexDao patMasterIndexDao;
    @Autowired
	private PatVisitDao patVisitDao;
    @Autowired
	private PatVisitIndexDao patVisitIndexDao;
    @Autowired
	private PatsInTransferringDao patsInTransferringDao;
    @Autowired
	private PatsInUnnursingDao patsInUnnursingDao;
    @Autowired
	private LiveRequisitionDao liveRequisitionDao;
    @Autowired
	private PatPrepaymentDao patPrepaymentDao;
	@Autowired
	private ClinicMasterDao clinicMasterDao;
	@Autowired
	private ClinicForRegistDao clinicForRegistDao;
	@Autowired
	private ClinicIndexDao clinicIndexDao;
	@Autowired
	private PriceListDao priceListDao;
	@Autowired
    private RegistCostDao registCostDao;
    @Autowired
    private MedicalCardConsumeMasterService medicalCardConsumeMasterService;
    @Autowired
    private MedicalVsPatientService medicalVsPatientService;
	@Autowired
	private CompanyDao companyDao;
	@Autowired
	private SysOrgDictDao sysOrgDictDao;
	@Autowired
	TInformationDao tInformationDao;
	@Autowired
	private OrgDeptDao orgDeptDao;
//	@Autowired
//	private  ClinicMasterService clinicMasterService;
	public PatMasterIndex get(String id) {
		return super.get(id);
	}
	
	public List<PatMasterIndex> findList(PatMasterIndex patMasterIndex) {
		return super.findList(patMasterIndex);
	}
	
	public Page<PatMasterIndex> findPage(Page<PatMasterIndex> page, PatMasterIndex patMasterIndex) {
		return super.findPage(page, patMasterIndex);
	}

	/**
	 * 保存挂号有关的数据
	 * @param patMasterIndex
	 * @param user
	 * @return List<ClinicMaster>
	 * @author 赵宁
	 */
	@Transactional(readOnly = false)
	public List<ClinicMaster> save(PatMasterIndex patMasterIndex,String clinicIds,User user,String prices,String payType) {
        String clinicNos="";
        int code=0;
		//保存病人基本信息
        if(!"0".equals(patMasterIndex.getCardPayFlag())){
            patMasterIndex.setInputCode(ChineseCharToEnUtils.getAllFirstLetter(patMasterIndex.getName()));
            patMasterIndex.updateOrgId();
            code=super.save(patMasterIndex);
        }
  		//获取当前日期最大的visitNo
		Integer no= clinicMasterDao.getMaxNo(DateUtils.getDate(),user.getOrgId());
		if(no!=null &&!no.equals("")){
			no=no+1;
		}else{
			no=1;
		}
		List<ClinicMaster> clinicMasterList = new ArrayList<ClinicMaster>();
		if(clinicIds!=null){
			String [] clinicId = clinicIds.split(",");
			String [] price = prices.split(",");
			if(clinicId.length>0){
				for(int i=0;i<clinicId.length;i++){
					ClinicForRegist clinicForRegist=clinicForRegistDao.get(clinicId[i]);
                    ClinicIndex clinicIndex=clinicIndexDao.get(clinicForRegist.getClinicIndexId());
					ClinicMaster clinicMaster = new ClinicMaster();
					clinicMaster.setOrgId(user.getOrgId());
					clinicMaster.setRegistType("0");//当日挂号
					clinicMaster.setPatientId(patMasterIndex.getId());
					clinicMaster.setAcctDateTime(new Date());
					clinicMaster.setVisitNo(no+"");
					clinicMaster.setVisitDate(new Date());
					clinicMaster.setRegistId(clinicId[i]);
					clinicMaster.setClinicNo(DateUtils.getDate("yyyyMMdd")+clinicMaster.getVisitNo());
					clinicMaster.setName(patMasterIndex.getName());
					clinicMaster.setSex(patMasterIndex.getSex());
					clinicMaster.setAge(patMasterIndex.getAge());
					clinicMaster.setFirstVisitIndicator(patMasterIndex.getFirstVisitIndicator());
					clinicMaster.setIdentity(patMasterIndex.getIdentity());
					clinicMaster.setChargeType(patMasterIndex.getChargeType());
					clinicMaster.setUnitInContract(patMasterIndex.getUnitInContract());
					clinicMaster.setDeptId(clinicIndex.getDeptId());
					clinicMaster.setDoctorId(clinicIndex.getDoctorId());
					clinicMaster.setClinicChage(Double.valueOf(price[i]));//实收费用
					if(!"0".equals(patMasterIndex.getCardPayFlag())){
						clinicMaster.setRemarks("0");//普通挂号
					}else{
						clinicMaster.setRemarks("1");//一卡通挂号
					}
					clinicMaster.setClinicType("0");
					if (clinicMaster.getIsNewRecord()){
						clinicMaster.preInsert();
						clinicMasterDao.insert(clinicMaster);
					}else{
						clinicMaster.preUpdate();
						clinicMasterDao.update(clinicMaster);
					}
                    clinicNos+=clinicMaster.getClinicNo()+",";
					no=no+1;
					//regist_cost插入数据
					//更新号表信息
					clinicForRegistDao.updateClinicRegist(clinicId[i]);
					//插入挂号费用记录
					String clinicIndexId=clinicForRegist.getClinicIndexId();
					String clinicItemId = clinicIndexDao.get(clinicIndexId).getClinicItemId();
					List<PriceList> priceLists=  priceListDao.findListPrice(clinicItemId);
					Double clinicFee=0.0;
                    if(priceLists.size()>0){
						for(int j=0;j<priceLists.size();j++){
							PriceList  priceList=priceLists.get(j);
							RegistCost registCost = new RegistCost();
							registCost.setClinicId(clinicMaster.getId());
							registCost.setType(payType);
                            clinicFee+=priceList.getPrice()*priceList.getAmount();
							registCost.setCost(priceList.getPrice()*priceList.getAmount());
							registCost.setSubjCode(priceList.getSubjCode());
							if (registCost.getIsNewRecord()){
								registCost.preInsert();
								registCostDao.insert(registCost);
							}else{
								registCost.preUpdate();
								registCostDao.update(registCost);
							}
						}
					}
                    if(patMasterIndex.isOneCard(clinicItemId,clinicFee,clinicMaster.getId())){
                        medicalCardConsumeMasterService.save(patMasterIndex.getMedicalCardConsumeMaster(),priceLists,clinicMaster.getClinicNo());
                    }
                    clinicMasterList.add(clinicMaster);
				}
                MedicalVsPatient medicalVsPatient=patMasterIndex.getMedicalVsPatient();
                if(medicalVsPatient!=null){
                    //保存医保与his关联
                    medicalVsPatient.setPatientId(patMasterIndex.getId());
                    if(clinicNos.length()>0){
                        medicalVsPatient.setClinicNo(clinicNos.substring(0,clinicNos.length()-1));
                    }
                    medicalVsPatientService.save(medicalVsPatient);
                }
			}
		}
		return  clinicMasterList;
	}


	@Transactional(readOnly = false)
	public int delete(PatMasterIndex patMasterIndex) {
		return super.delete(patMasterIndex);
	}

	/**
	 * 门诊修改病人信息
	 * @param patMasterIndex
	 * @return
	 */
    @Transactional(readOnly = false)
    public int updateInfo(PatMasterIndex patMasterIndex) {
		patMasterIndex.preUpdate();
		patMasterIndexDao.update(patMasterIndex);
		ClinicMaster clinicMaster1 = clinicMasterDao.get(patMasterIndex.getClinicId());
		String doctorId=clinicMaster1.getDoctorId();
		ClinicMaster clinicMaster = new ClinicMaster();
		if(StringUtils.isBlank(doctorId)){
			User user=UserUtils.getUser();
			clinicMaster.setDoctorId(user.getId());
            clinicMaster.setClinicType("1");
		}
		clinicMaster.setName(patMasterIndex.getName());
		clinicMaster.setAge(patMasterIndex.getAge());
		clinicMaster.setSex(patMasterIndex.getSex());
		clinicMaster.setChargeType(patMasterIndex.getChargeType());
		clinicMaster.setIdentity(patMasterIndex.getIdentity());
		clinicMaster.setUnitInContract(patMasterIndex.getUnitInContract());
		clinicMaster.setPatientId(patMasterIndex.getId());
		clinicMaster.preUpdate();
		int mun = clinicMasterDao.updateClinicPatInfo(clinicMaster);
        return mun;
    }
	@Transactional(readOnly = false)
	public int saveUserBasicInfo(PatMasterIndex patMasterIndex) {
		int num = 0;
		if(patMasterIndex.gettInformation()!=null&& StringUtils.isNotBlank(patMasterIndex.gettInformation().getId())){
//			TInformation tInformation=tInformationDao.get(patMasterIndex.gettInformation().getId());
//			tInformation.setHealthexamDate(patMasterIndex.gettInformation().getHealthexamDate());
//			tInformation.setType(patMasterIndex.gettInformation().getType());
//			tInformation.setTeam(patMasterIndex.gettInformation().getTeam());
//			tInformation.setTeamGroup(patMasterIndex.gettInformation().getTeamGroup());
//			tInformation.setPayType(patMasterIndex.gettInformation().getPayType());
//			tInformation.setUnifiedPrice(patMasterIndex.gettInformation().getUnifiedPrice());
//			tInformation.setId(patMasterIndex.gettInformation().getId());
			patMasterIndex.gettInformation().preUpdate();
			patMasterIndex.gettInformation().setClinicId(patMasterIndex.getClinicId());
			tInformationDao.update(patMasterIndex.gettInformation());
		}
		num = super.save(patMasterIndex);
		return num;
	}

	public Page<PatMasterIndex> queryPatientTj(Page<PatMasterIndex> patMasterIndexPage, PatMasterIndex patMasterIndex) {
		patMasterIndex.updateOrgId();
		patMasterIndex.setPage(patMasterIndexPage);
		patMasterIndexPage.setList(patMasterIndexDao.findListTJList(patMasterIndex));
		return patMasterIndexPage;
	}

	/**
	 * 门诊挂号打印
 	 * @param ids
	 * @return String
	 * @author 赵宁
	 */
	public String printRegisit(String ids){
		User user = UserUtils.getUser();
		String [] id = ids.split(",");
		String printPath = "";
		for(int i = 0;i<id.length;i++){
			String hospital =user.getCompany().getOrgName();
			ClinicMaster clinicMaster=clinicMasterDao.get(id[i]);
			//查询费用
			RegistCost registCost = new RegistCost();
			registCost.setClinicId(id[i]);
			Double registFee= 0.0;//挂号费
			Double clinicFee=0.0;//诊查费
			List<RegistCost> registCosts = registCostDao.findList(registCost);
			for(int j=0;j<registCosts.size();j++){
				String subjCode=registCosts.get(j).getSubjCode();
                if(subjCode!=null && subjCode.equals("A")){
					registFee=registCosts.get(j).getCost();
				}else if(subjCode!=null && subjCode.equals("C")){
					clinicFee=registCosts.get(j).getCost();
				}

			}
			Map map = new HashMap();
			map.put("hospital",hospital);
			map.put("name",clinicMaster.getName());//患者姓名
			map.put("age",clinicMaster.getAge());//患者年龄
			String sex = DictUtils.getDictLabels(clinicMaster.getSex(),"SEX_DICT","");
			map.put("sex",sex);
			map.put("clinicNo",clinicMaster.getClinicNo());//门诊号
			map.put("deptName",orgDeptDao.get(clinicMaster.getDeptId()).getDeptName());//科别
			map.put("userName",user.getName());

			map.put("registFee",registFee);//
			map.put("clinicFee",clinicFee);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar calendar =Calendar.getInstance();
			calendar.setTime(clinicMaster.getCreateDate());
			int year = calendar.get(Calendar.YEAR);
			int month = calendar.get(Calendar.MONTH)+1;
			int day=calendar.get(Calendar.DAY_OF_MONTH);
			map.put("year",year);//挂号时间
			map.put("month",month);//挂号时间
			map.put("day",day);//挂号时间
			List list = new ArrayList();
			list.add("hello");
			list.add("cost");
			printPath = PrintPdfUtils.previewPdf(user.getId(), "his/todayRegister/todayRegist.jasper", map, list, "todayRegister");
		}
		return printPath;
	}

	/**
	 * emr接口获取病人列表--病人基本信息
	 * @param baseDto
	 * @return
	 * @author 赵宁
	 */
	public List<BaseDto> findPatList(BaseDto baseDto){
		return dao.findPatList(baseDto);
	}

	/**
	 * emr接口获取病人列表--病人住院信息
	 * @param baseDto
	 * @return
	 * @author 赵宁
	 */
	public List<BaseDto> findPatVisitList(BaseDto baseDto){
		return dao.findPatVisitInfo(baseDto);
	}

	/**
	 * emr接口更新病人基本信息
	 * @param visitId
	 * @return
	 */
	public List<BaseDto> updateBasicInfo(String visitId){
		return dao.updateBascInfo(visitId);
	}

	/**
	 * emr接口更新病人住院信息
	 * @param visitId
	 * @return
	 * @author  赵宁
	 */
	public List<BaseDto> updatePatInfo(String visitId){
		return dao.updatePatInfo(visitId);
	}
	/**
	 * 患者入院登记处-取消登记功能
	 * @param patMasterIndex
	 * @return
	 * @author CTQ
	 * @date 2017-07-19 14:04:23
	 */
	@Transactional(readOnly = false)
	public StringData cancelRegister(PatMasterIndex patMasterIndex){
		StringData data = new StringData();
		int num=0;
		if(patMasterIndex!=null){
			PatVisit patVisit = patVisitDao.getPatientInfo(patMasterIndex.getId());
			if (patVisit!=null){
				PatPrepayment patPrepayment = new PatPrepayment();
				patPrepayment.setPatientId(patMasterIndex.getId());
				patPrepayment.setVisitId(patVisit.getId());
				patPrepayment.setVisitNo(patVisit.getVisitNo());
				PatPrepayment patPrepayments = patPrepaymentDao.findAmount(patPrepayment);
				if(StringUtils.isNotBlank(patVisit.getBedNo())&&StringUtils.isNotBlank(patVisit.getWardCode())&&patVisit.getWardFlag().equals("1")){
					/**判断病人是否已入病区*/
					data.setCode("ward");
					data.setData("该病人已入病区，不能进行取消登记操作！");
				}else if(StringUtils.isNotBlank(patVisit.getDeptStayed())&&patVisit.getDeptFlag().equals("1")){
					/**判断病人是否已入科*/
					data.setCode("dept");
					data.setData("该病人已入科室，不能进行取消登记操作！");
				}else if(patPrepayments!=null&&patPrepayments.getAmount()!=null&&patPrepayments.getAmount()>0){
					 /**判断病人是否已交预交金*/
					data.setCode("info");
					data.setData("该病人已缴纳预交金，不能进行取消登记操作！");
				}else{
					num = cancel(patVisit);

				}
			}else{
				/**判断病人是否已进行入院登记*/
				data.setCode("warn");
				data.setData("该病人未进行入院患者登记，不能进行取消登记操作！");
			}
		}
		if (num>0){
			data.setCode("success");
			data.setData("取消登记成功！");
		}
		return data;
	}

	/**
	 * 取消登记公用方法
	 * @param patVisit
	 * @return
	 * @CTQ
	 * @date 2017-07-19 14:03:49
	 */

	private int cancel(PatVisit patVisit){
		int num = 0;
		/**删除pat_visit_index信息*/
		num+=patVisitIndexDao.delByVisitId(patVisit.getId());
		/**删除pat_visit信息*/
		num+=patVisitDao.delete(patVisit);
		/**删除pats_in_transferring信息*/
		PatsInTransferring patsInTransferring = new PatsInTransferring();
		patsInTransferring.setPatientId(patVisit.getPatientId());
		patsInTransferring.setVisitId(patVisit.getId());
		patsInTransferring.updateOrgId();
		num+=patsInTransferringDao.deleteByParam(patsInTransferring);
		/**删除pats_in_unnursing信息*/
		PatsInUnnursing patsInUnnursing = new PatsInUnnursing();
		patsInUnnursing.setPatientId(patVisit.getPatientId());
		patsInUnnursing.setVisitId(patVisit.getId());
		patsInUnnursing.updateOrgId();
		num+=patsInUnnursingDao.deleteByParam(patsInUnnursing);
		/**修改住院通知单状态*/
		num += liveRequisitionDao.upDateInFlge(patVisit.getClinicId()!=null?patVisit.getClinicId():"","0");
		return num;
	}


}